package com.tiancheng.trade.order.controller.api;

import com.tiancheng.trade.commom.core.data.Result;
import com.tiancheng.trade.commom.core.enums.PaymentChannelEnum;
import com.tiancheng.trade.commom.core.utils.JsonUtil;
import com.tiancheng.trade.order.bo.OrderBO;
import com.tiancheng.trade.order.bo.SubOrderBO;
import com.tiancheng.trade.order.enums.BusinessTypeEnum;
import com.tiancheng.trade.order.enums.SystemSourceEnum;
import com.tiancheng.trade.order.model.IntOrder;
import com.tiancheng.trade.order.service.IntOrderService;
import com.tiancheng.trade.order.service.IntSubOrderService;
import com.tiancheng.trade.order.util.CommonUtil;
import com.tiancheng.trade.order.util.ObjectConvertUtil;
import com.tiancheng.trade.order.vo.api.*;
import com.tiancheng.trade.order.vo.api.res.RefundCreateResVO;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 订单业务侧api接口
 */
@RestController
@RequestMapping("/api/int")
@Validated
@Slf4j
public class IntOrderApiController {

    @Resource
    private IntOrderService intOrderService;
    @Resource
    private IntSubOrderService intSubOrderService;

    /**
     * 创建订单
     *
     * @param orderVO
     * @return
     */
    @PostMapping(value = "/create", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result create(@RequestBody @Valid OrderVO orderVO) {
        // 生成主订单业务对象
        OrderBO orderBO = this.toOrderBO(orderVO);
        if(StringUtils.isEmpty(orderBO.getSystemSource())){
            orderBO.setSystemSource(SystemSourceEnum.YOUYUNNAN.getCode());
        }

        if(StringUtils.isEmpty(orderBO.getBusinessType())){
            orderBO.setBusinessType(BusinessTypeEnum.B2C.getCode());
        }
        // 生成子订单业务对象列表
        List<SubOrderBO> subOrderBOS = this.toSubOrderBO(orderVO);

        try {
            // 支付渠道 : 目前只有PayPal
            orderBO.setPayChannel(PaymentChannelEnum.PAYPAL.getCode());
            log.info("判断版本信息 客户端：{} 传入版本号：{} 版本支付渠道结果-->>{}",orderVO.getAppType(),orderVO.getAppVersion(), orderBO.getPayChannel());
            String orderId = intOrderService.create(orderBO, subOrderBOS);
            return Result.success(orderId);
        } catch (Exception e) {
            throw e;
        }
    }


    /**
     * 功能描述: 关闭订单
     * 1、更新订单状态
     * @param: 流水号：flowId,用户id：userId
     * @return:
     */
    @PostMapping("/close")
    public Result closeOrder(@RequestBody @Valid CloseOrderVO closeOrderVO) {
        boolean result = intOrderService.closeOrder(closeOrderVO);
        if (result) {
            return Result.success();
        } else {
            return Result.fail("关闭失败");
        }
    }

    /**
     * 创建并执行退款
     * @param refundVO
     * @return
     */
    @PostMapping(value = "/refund", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result execute(@RequestBody @Valid RefundVO refundVO) {
        RefundCreateResVO resVO = intOrderService.refundOrder(refundVO);
        return Result.success(resVO);
    }


    /**
     * 查询单笔主订单
     *
     * @param uid
     * @param orderId
     * @return
     */
    @GetMapping("/get")
    public Result get(@RequestParam("order_id") @NotEmpty String orderId,
                      @RequestParam("uid") @NotEmpty String uid) {
        IntOrder order = intOrderService.get(uid, orderId);
        Map<String, Object> res = JsonUtil.fromJson(JsonUtil.toJsonString(order), Map.class);
        res.put("pay_left_second", Duration.between(LocalDateTime.now(),
                order.getPayExpiryTime()).toMillis() / 1000);
        return Result.success(res);
    }


    /**
     * 根据订单号查号询主订单及子订单数据
     *
     * @param orderId
     * @return
     */
    @GetMapping("/sub/findByOrderId")
    public Result findByOrderId(@RequestParam("order_id") String orderId) {
        return Result.success(intOrderService.findByOrderId(orderId));
    }

    /**
     * 参数转成主订单业务对象
     *
     * @param orderVO
     * @return
     */
    private OrderBO toOrderBO(OrderVO orderVO) {
        OrderBO orderBO = ObjectConvertUtil.convert(orderVO, OrderBO.class).get();
        orderBO.setIsTest(Objects.isNull(orderVO)?0:1);
        orderBO.setOrderAmount(orderVO.getSubOrders().stream().mapToInt(SubOrderVO::getSubOrderAmount).sum());
        orderBO.setIsCoupon(CollectionUtils.isEmpty(orderVO.getCoupons())?0:1);
        orderBO.setDiscount(0);
        if(StringUtils.isEmpty(orderBO.getOriginalOrderId())) {
            orderBO.setOriginalOrderId("0");
        }

        // 默认使用第一笔子订单的商品名称作为订单名称
        if (StringUtils.isEmpty(orderBO.getOrderName())) {
            orderBO.setOrderName(orderVO.getSubOrders().get(0).getProductName());
        }
        // 对orderName进行制表符、换行符、前后空格处理
        orderBO.setOrderName(CommonUtil.trim(orderBO.getOrderName()));
        return orderBO;
    }

    /**
     * 参数转成子订单业务对象
     *
     * @param orderVO
     * @return
     */
    private List<SubOrderBO> toSubOrderBO(OrderVO orderVO) {
        List<SubOrderBO> subOrderBOS = orderVO.getSubOrders().stream().map(subOrderVO -> {
            SubOrderBO subOrderBO = ObjectConvertUtil.convert(subOrderVO, SubOrderBO.class).get();
            subOrderBO.setOrderId(orderVO.getOrderId());
            subOrderBO.setOrderSource(orderVO.getOrderSource());
            subOrderBO.setCreateTime(orderVO.getCreateTime());
            subOrderBO.setIsCoupon(subOrderVO.getCoupons() != null && subOrderVO.getCoupons().size() > 0?1:0);
            subOrderBO.setDiscount(0);    //初始化
            // 对名称进行制表符、换行符、前后空格处理
            subOrderBO.setProductName(CommonUtil.trim(subOrderBO.getProductName()));
            subOrderBO.setProductDetail(CommonUtil.trim(subOrderBO.getProductDetail()));
            if(StringUtils.isEmpty(subOrderBO.getOriginalSubOrderId())) {
                subOrderBO.setOriginalSubOrderId("0");
            }
            return subOrderBO;
        }).collect(Collectors.toList());
        return subOrderBOS;
    }

    /**
     * 查询paypal支付信息:  主动向paypal支付平台发起查询
     * @param orderId
     * @return
     */
    @GetMapping("/getPaypalInfo")
    public Result getPaypal(@RequestParam("order_id") String orderId){
        log.info("查询订单号，orderId :{}", orderId);
        return  intOrderService.getPaypalInfo(orderId);
    }


    /**
     * 查询指定子订单
     *
     * @param subOrderId
     * @return
     */
    @GetMapping("/sub/{subOrderId}")
    public Result getSubOrder(@PathVariable String subOrderId) {
        return Result.success(intSubOrderService.getWithJoin(subOrderId));
    }


    /**
     * 订单状态上报
     *
     * @return
     */
    @PostMapping("/reportOrderStatus")
    public Result reportOrderStatus(@RequestBody @Valid ReportOrderStatusVO date) {
        intSubOrderService.reportOrderStatus(date);
        return Result.success();
    }
}
